package oss

import (
	"fmt"
	"gitee.com/slclub/aliyun-oss/conf"
	"gitee.com/slclub/aliyun-oss/logq"
	"gitee.com/slclub/aliyun-oss/utils"
	"net/http"
	"net/url"
)

type HTTP_METHOD string

const (
//HTTP_PUT    = "PUT"
//HTTP_GET    = "GET"
//HTTP_DELETE = "DELETE"
//HTTP_POST   = "POST"
)

func getAuthorization(method HTTP_METHOD, fileName string) string {
	authorization := "OSS " + conf.Config.OSS.AccessKeyId + ":" +
		getSignature(
			method,
			"",
			"",
			utils.GetDateGMT(),
			"",
			""+conf.Config.OSS.BucketName+"/"+fileName)

	logq.DebugF("conf oss [%v]", authorization)

	return authorization
}

func getSignature(verb HTTP_METHOD, md5 string, contentType string, date string, canonicalizedOSSHeaders string, canonicalizedOSSResource string) string {
	strSign := fmt.Sprintf("%v\n%v\n%v\n%v\n%v%v", verb, md5, contentType, date, canonicalizedOSSHeaders, canonicalizedOSSResource)

	hmacSign := utils.HmacSHA1UTF8(strSign, conf.Config.OSS.AccessKeySecret)

	fmt.Printf("\n\nsign-hmac [%v]\n", hmacSign)
	return hmacSign
}

func GetBucketHost() string {
	return fmt.Sprintf("%v://%v.oss-%v.aliyuncs.com", conf.Config.OSS.Scheme, conf.Config.OSS.Bucket, conf.Config.OSS.RegionId)
}

func OssObject(method HTTP_METHOD, param *url.Values, file_path string) *http.Response {

	req, err := http.NewRequest(http.MethodGet, GetBucketHost()+"?"+param.Encode(), nil)
	if err != nil {
		logq.ErrorF("OSS(ListObjectV2)--生成Request失败，原因:%v", err)
	}

	req.Header.Set("Content-Type", "text/plain")
	req.Header.Set("Host", GetBucketHost())
	req.Header.Set("Date", utils.GetDateGMT())
	req.Header.Set("Authorization", getAuthorization(method, file_path))
	client := &http.Client{}
	response, err := client.Do(req)
	if err != nil {
		logq.Error("[]")
	}
	return response
}
